<?php declare(strict_types=1);

namespace app\common\service;

use app\admin\model\Page;
use app\common\model\Site;
use app\common\model\Nav;

class SiteService
{
    /**
     * 获取网站配置信息
     * @return void
     */
    public function getSiteConfig()
    {
        $model = new Site();
        return $model->field('site_name,site_title,keywords,description,site_url,qq,mobile,weibo,douyin,xiaohongshu,address,icp')->find(1);
    }

    /**
     * 获取导航
     * @return Nav[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNavList()
    {
        $model = new Nav();
        $items = $model->where(['status'=>1, 'parent_id'=>0])
            ->field('id,parent_id,name,linkurl,keywords,description,sort')
            ->order(['sort'=>'asc'])
            ->select()
            ->each(function($item) {
                $item['child_nav'] = $this->getChildNav($item->id);
                return $item;
            });

        return $items;
    }

    /**
     * 获取子导航
     * @param $pid
     * @return void
     */
    public function getChildNav($pid)
    {
        $model = new Nav();
        $items = $model->where(['status'=>1, 'parent_id'=>$pid])
            ->field('id,parent_id,name,linkurl,keywords,description,sort')
            ->order(['sort'=>'asc'])
            ->select();
        if (!empty($items)) {
            $pageModel = new Page();
            foreach ($items as &$item) {
                $item->page_id = $pageModel->where('nav_id', $item->id)->value('id') ?? 0;
            }
        }
        return $items;
    }

    /**
     * 获取栏目信息
     * @param $id
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNav($id)
    {
        $model = new Nav();
        $item = $model->where(['id'=>$id, 'status'=>1])->find();
        if (!empty($item)) {
            if ($item->parent_id) {
                $item['child_nav'] = $this->getChildNav($item->id);
            }
        }
        return $item;
    }
}